module WsClient

	class HeadersHash
		def initialize(hash = {})
			@hash = convert_hash(hash)
		end
		
		def [](key)
			@hash[IndifferentKey.new(key)]
		end
		
		def []=(key, value)
			@hash[IndifferentKey.new(key)] = value
		end
		
		def keys
			@hash.keys.map { |key| key.original }
		end
		
		def values
			@hash.values
		end
		
		def update(hash)
			@hash.update(convert_hash(hash))
			self
		end
		
		def to_hash
			Hash[@hash.map { |key, value| [key.original, value] }]
		end
		
		private
		
		def convert_hash(hash)
			hash = hash.to_hash
			Hash[hash.map { |key, value| [IndifferentKey.new(key), value] }]
		end
		
		class IndifferentKey
			attr_reader :original, :indifferent
		
			def initialize(key)
				@original = key
				@indifferent = key.to_s.downcase
			end
			
			def to_s
				@original.to_s
			end
			
			def hash
				@indifferent.hash
			end
			
			def eql?(other)
				if other.is_a?(IndifferentKey)
					other.indifferent == @indifferent
				else
					false
				end
			end
			
			def ==(other)
				other = if other.is_a?(IndifferentKey)
					other.indifferent
				else
					other.to_s.downcase
				end
			
				other == @indifferent
			end
		end
	end

end
